﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
namespace UrlRewriter
{
    public class UrlRewriterModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            //路径中如果包含‘%’号，则在进入BeginRequest事件前就会报400（Bad Request）错误
            app.PostAuthorizeRequest += new EventHandler(UrlRewrite);
        }

        void UrlRewrite(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            string path = app.Request.Path;
            var header = app.Request.Headers;

            //获取所有重写规则
            IList<UrlConfig> configs = Config.Instance.Elements;

            //规则检查
            foreach (UrlConfig config in configs)
            {
                Regex reg = new Regex(config.FromUrl, RegexOptions.IgnoreCase);
                if (reg.IsMatch(path))
                {
                    string toUrl = reg.Replace(path, config.ToUrl);
                    ReWritePath(app.Context, toUrl);
                    break;
                }
            }
        }

        private void ReWritePath(HttpContext context, string toUrl)
        {
            string destUrl = toUrl;

            if (context.Request.QueryString.Count != 0)
            {
                if (destUrl.IndexOf('?') == -1)
                {
                    destUrl += "?" + context.Request.QueryString.ToString();
                }
                else
                {
                    destUrl += "&" + context.Request.QueryString.ToString();
                }
            }
            context.RewritePath(destUrl);
        }



        public void Dispose()
        {

        }
    }
}
